<template>
  <div class="container" style="padding: 20px">
    <!-- 搜索框 -->
    <div style="display: flex; align-items: center; margin-bottom: 20px;">
      <el-input v-model="searchQuery" placeholder="请输入关键字进行搜索" style="width: 300px;"></el-input>
      <el-button @click="filteredTableData" class="centered-button" style="margin-left: 10px;">搜索</el-button>
      <el-button @click="openAddDialog" class="centered-button" style="margin-left: 10px;">增加航班</el-button>
      <!--更新模型请求-->
      <div class="restartModel">
        <el-button type="primary" @click="newModel">更新后台模型</el-button>
      </div>
    </div>

    <!-- 表格 -->
    <el-table :data="currentTableData" border style="width: 100%">
      <el-table-column fixed prop="airline" label="航空公司" width="150">
        <template #default="scope">
          <el-input v-if="scope.row.editing" v-model="scope.row.airline"></el-input>
          <span v-else>{{ scope.row.airline }}</span>
        </template>
      </el-table-column>

      <!-- 其他列省略 -->
      <el-table-column prop="startDate" label="出发日期" width="120">
        <template #default="scope">
          <el-input v-if="scope.row.editing" v-model="scope.row.startDate"></el-input>
          <span v-else>{{ scope.row.startDate }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="airlineNum" label="航班号" width="120">
        <template #default="scope">
          <el-input v-if="scope.row.editing" v-model="scope.row.airlineNum"></el-input>
          <span v-else>{{ scope.row.airlineNum }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="duration" label="旅途时长" width="120">
        <template #default="scope">
          <el-input v-if="scope.row.editing" v-model="scope.row.duration"></el-input>
          <span v-else>{{ scope.row.duration }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="route" label="出发-到达机场" width="300">
        <template #default="scope">
          <el-input v-if="scope.row.editing" v-model="scope.row.route"></el-input>
          <span v-else>{{ scope.row.route }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="机票价格" width="120">
        <template #default="scope">
          <el-input v-if="scope.row.editing" v-model="scope.row.price"></el-input>
          <span v-else>{{ scope.row.price }}</span>
        </template>
      </el-table-column>

      <el-table-column fixed="right" label="操作" width="200">
        <template #default="scope">
          <el-button v-if="scope.row.editing" @click="saveRow(scope.row)" type="text" size="small">保存</el-button>
          <el-button v-if="scope.row.editing" @click="cancelEdit(scope.row)" type="text" size="small">取消</el-button>
          <el-button v-else @click="editRow(scope.row)" type="text" size="small">编辑</el-button>
          <el-button @click="deleteRow(scope.row)" type="text" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <el-pagination
        background
        layout="prev, pager, next"
        :total="filteredData.length"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
        style="margin-top: 20px; text-align: center;">
    </el-pagination>

    <!-- 增加航班的对话框 -->
    <el-dialog :visible.sync="addDialogVisible" v-model="addDialogVisible"  title="增加航班" display: block>
      <el-form :model="newFlight">
        <el-form-item label="航班号">
          <el-input v-model="newFlight.flight_no"></el-input>
        </el-form-item>
        <el-form-item label="航空公司">
          <el-input v-model="newFlight.airline"></el-input>
        </el-form-item>
        <el-form-item label="出发城市">
          <el-input v-model="newFlight.departure_city"></el-input>
        </el-form-item>
        <el-form-item label="出发机场">
          <el-input v-model="newFlight.departure_airport"></el-input>
        </el-form-item>
        <el-form-item label="到达城市">
          <el-input v-model="newFlight.arrival_city"></el-input>
        </el-form-item>
        <el-form-item label="到达机场">
          <el-input v-model="newFlight.arrival_airport"></el-input>
        </el-form-item>
        <el-form-item label="起飞时间">
          <el-input v-model="newFlight.departure_time"></el-input>
        </el-form-item>
        <el-form-item label="起飞日期">
          <el-input v-model="newFlight.departure_date"></el-input>
        </el-form-item>
        <el-form-item label="到达日期">
          <el-input v-model="newFlight.arrival_date"></el-input>
        </el-form-item>
        <el-form-item label="到达时间">
          <el-input v-model="newFlight.arrival_time"></el-input>
        </el-form-item>
        <el-form-item label="到达价格">
          <el-input v-model="newFlight.price"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addFlight">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {onMounted, ref} from 'vue';
import axios from 'axios';
import {
  ElMessage,
  ElButton,
  ElDialog,
  ElInput,
  ElForm,
  ElFormItem,
  ElTable,
  ElTableColumn,
  ElMessageBox,
  ElPagination
} from 'element-plus';

export default {
  components: {
    ElButton,
    ElDialog,
    ElInput,
    ElForm,
    ElFormItem,
    ElTable,
    ElTableColumn,
    ElPagination
  },

  setup() {
    const searchQuery = ref('');
    const tableData = ref([]);
    const filteredData = ref([]);
    const addDialogVisible = ref(false);
    const currentTableData = ref([]);
    const newFlight = ref({
      airline: '',
      startDate: '',
      airlineNum: '',
      duration: '',
      route: '',
      price: ''
    });

    // 分页相关变量
    const currentPage = ref(1);
    const pageSize = ref(10);

    const fetchFlightData = async () => {
      try {
        const response = await axios.get('http://localhost:8000/adminUsers/manageFlight/data');
        tableData.value = response.data.data;
        filteredData.value = response.data.data.slice();
        filteredData.value.forEach(item => {
          item.editing = false;
        });
        handlePageChange(currentPage.value);
      } catch (error) {
        console.error('获取航班数据失败:', error);
      }
    };

    const openAddDialog = () => {
      addDialogVisible.value = true;
    };

    const addFlight = () => {
      console.log(newFlight.value);
      axios.post('http://localhost:8000/adminUsers/manageFlight/add', newFlight.value)
          .then(() => {
            ElMessage.success('增加成功!');
            addDialogVisible.value = false;
            fetchFlightData();
            newFlight.value = {
              flight_no:'',
              airline:'',
              departure_city:'',
              departure_airport:'',
              arrival_city:'',
              arrival_airport:'',
              departure_time:'',
              departure_date:'',
              arrival_date:'',
              arrival_time:'',
              price:''
            };
          })
          .catch(error => {
            console.error('增加失败:', error);
            ElMessage.error('增加失败!');
          });
    };

    const editRow = (row) => {
      cancelAllEdits();
      row.olduid = row.uid;
      row.editing = true;
    };

    const saveRow = async (row) => {
      try {
        row.editing = false;
        console.log(row)
        await axios.post(`http://localhost:8000/adminUsers/manageFlight/save`, row);
        ElMessage.success('保存成功!');
      } catch (error) {
        console.error('保存失败:', error);
        ElMessage.error('保存失败!');
        await fetchFlightData();
      }
    };

    const cancelEdit = (row) => {
      row.editing = false;
      fetchFlightData();
    };

    const cancelAllEdits = () => {
      filteredData.value.forEach(item => {
        item.editing = false;
      });
    };

    const deleteRow = async (row) => {
      try {
        await ElMessageBox.confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        await axios.post(`http://localhost:8000/adminUsers/manageFlight/delete`, row);
        await fetchFlightData();
        ElMessage.success('删除成功!');
      } catch (error) {
        console.error('删除失败:', error);
        ElMessage.error('删除失败!');
      }
    };

    const filteredTableData = () => {
      if (!searchQuery.value) {
        filteredData.value = tableData.value.slice();
      } else {
        filteredData.value = tableData.value.filter(item =>
            Object.values(item).some(value =>
                String(value).toLowerCase().includes(searchQuery.value.toLowerCase())
            )
        );
      }
      handlePageChange(currentPage.value);
    };

    const handlePageChange = (page) => {
      currentPage.value = page;
      const start = (currentPage.value - 1) * pageSize.value;
      const end = start + pageSize.value;
      currentTableData.value = filteredData.value.slice(start, end);
    };

    onMounted(fetchFlightData);

    return {
      searchQuery,
      tableData,
      filteredData,
      addDialogVisible,
      newFlight,
      fetchFlightData,
      openAddDialog,
      addFlight,
      editRow,
      saveRow,
      cancelEdit,
      cancelAllEdits,
      deleteRow,
      filteredTableData,
      currentPage,
      pageSize,
      handlePageChange,
      currentTableData
    };
  },

  mounted() {
    this.fetchFlightData();
  },
  methods:{
    async newModel(){
      const response = await axios.get('http://localhost:8000/adminUsers/model/new', {
      });
      if(response.status === 200){
        ElMessage({
          message: '成功更新后台模型.',
          type: 'success',
        })
      }
    },
  }
};
</script>

<style scoped>
.restartModel{
  margin-left: 30px;
}
.centered-button {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
